package com.hjy.wechatdevelopermode.api;

import cn.hutool.http.HttpUtil;
import com.hjy.wechatdevelopermode.menu.Button;
import com.hjy.wechatdevelopermode.menu.CommonButton;
import com.hjy.wechatdevelopermode.menu.ComplexButton;
import com.hjy.wechatdevelopermode.menu.Menu;
import com.hjy.wechatdevelopermode.process.CoreService;
import com.hjy.wechatdevelopermode.util.AccessTokenUtil;
import com.hjy.wechatdevelopermode.util.WeiXinParamesUtil;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * @CopyRight: 版权所有
 * @Author: hejinyi
 * @Description:
 * @Date: 2020/5/21
 */
@RestController
@RequestMapping(value = "store/weChat/callback")
@EnableSwagger2
@Api(value= "微信开发者模式",tags="微信开发者模式接口")
public class WeChatCallBackController {

    private static final Logger logger = LoggerFactory.getLogger(WeChatCallBackController.class);

    @Autowired
    private AccessTokenUtil accessTokenUtil;
    @Autowired
    private CoreService coreService;

  //  @Autowired
 //   private StoreConfigService storeConfigService;

    /**
     * 校验信息是否是从微信服务器发出
     *
     * @param request
     * @param response
     */
    @GetMapping(value = "/doDeveloperMode")
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        logger.info("微信校验开发者模式........");
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("微信校验开发者模式,消息UTF-8格式化错误......e={}",e);
        }
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");
        logger.info("微信校验开发者模式...signature={},timestamp={},nonce={},echostr={}",signature,timestamp,nonce,echostr);

        try (PrintWriter writer = response.getWriter()) {
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (!WeiXinParamesUtil.checkSignature(WeiXinParamesUtil.token,signature, timestamp, nonce)) {
                logger.error("微信接入验证失败!");
            }else{
                logger.info("微信校验开发者模式........校验成功,将echostr={}原路返回",echostr);
                writer.write(echostr);
            }

        }catch (Exception e) {
            logger.info("微信校验开发者模式........校验失败,e={}",e.getMessage());
            e.printStackTrace();
            logger.error("IOException", e);
        }
    }

    /**
     * 微信服务器处理消息
     *
     * @param request
     * @param response
     */
    @PostMapping(value = "/doDeveloperMode")
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        Long beginTime = System.currentTimeMillis();
        logger.info("开始处理微信传入的用户消息........,beginTime={}",beginTime);
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("接受微信传入的用户消息,消息UTF-8格式化错误......e={}",e);
        }

        // 调用核心业务类接收消息、处理消息
        String respMessage = coreService.processRequest(request);
        try (PrintWriter writer = response.getWriter()) {
            if (StringUtils.isNotBlank(respMessage)) {
                writer.write(respMessage);
            } else {
                writer.write("服务器繁忙,请稍后重试！");
            }
            logger.info("处理微信传入的用户消息结束........,time={}",beginTime-System.currentTimeMillis());
        } catch (Exception e) {
            logger.error("处理微信传入的用户消息错误........,time={},e={}",beginTime-System.currentTimeMillis(),e);
        }
    }

    /**
     * 创建菜单
     *
     * @return 0表示成功，其他值表示失败
     */
    @PostMapping(value = "/createMenu")
    public boolean createMenu(String tenantId) {

//        BaseConfigDto baseConfigDto = storeConfigService.queryById(tenantId);
//
//        String AppID = baseConfigDto.getWxAppid();
//        String AppSecret = baseConfigDto.getWxAppSecret();

        String AppID = WeiXinParamesUtil.wxAppid;
        String AppSecret = WeiXinParamesUtil.appsecret;

        String menu_create_url =  WeiXinParamesUtil.menu_create_url;

        String accessToken = accessTokenUtil.getAccessToken(AppID,AppSecret);

        Menu menu = getMenu();

        // 拼装创建菜单的url
        String url =menu_create_url.replace("ACCESS_TOKEN", accessToken);

        // 将菜单对象转换成json字符串
        // false表示不跳过空值
        cn.hutool.json.JSONObject json = cn.hutool.json.JSONUtil.parseObj(menu, true);
        logger.info("菜单....menu={}",json.toString());

        String result= HttpUtil.post(url, json.toString());
        cn.hutool.json.JSONObject jsonObject = cn.hutool.json.JSONUtil.parseObj(result);
        if(null != jsonObject){
            if(0 != jsonObject.getInt("errcode")){
                logger.error("创建菜单失败......返回={}",jsonObject.toString());
                return false;
            }else{
                return true;
            }
        }

        return false;
    }

    /**
     * 删除菜单
     *
     * @return 0表示成功，其他值表示失败
     */
    @PostMapping(value = "/deleteMenu")
    public boolean deleteMenu(String tenantId) {

//        BaseConfigDto baseConfigDto = storeConfigService.queryById(tenantId);
//
//        String AppID = baseConfigDto.getWxAppid();
//        String AppSecret = baseConfigDto.getWxAppSecret();

        String AppID = WeiXinParamesUtil.wxAppid;
        String AppSecret = WeiXinParamesUtil.appsecret;

        String delete_menu_create_url =  WeiXinParamesUtil.delete_menu_create_url;

        String accessToken = accessTokenUtil.getAccessToken(AppID,AppSecret);

        // 拼装创建菜单的url
        String url =delete_menu_create_url.replace("ACCESS_TOKEN", accessToken);

        String result= HttpUtil.get(url);
        cn.hutool.json.JSONObject jsonObject = cn.hutool.json.JSONUtil.parseObj(result);
        if(null != jsonObject){
            if(0 != jsonObject.getInt("errcode")){
                logger.error("删除菜单失败......返回={}",jsonObject.toString());
                return false;
            }else{
                return true;
            }
        }

        return false;
    }

    /**
     * 查询菜单
     *
     * @return 0表示成功，其他值表示失败
     */
    @PostMapping(value = "/queryMenu")
    public String queryMenu(String tenantId) {

//        BaseConfigDto baseConfigDto = storeConfigService.queryById(tenantId);
//
//        String AppID = baseConfigDto.getWxAppid();
//        String AppSecret = baseConfigDto.getWxAppSecret();

        String AppID = WeiXinParamesUtil.wxAppid;
        String AppSecret = WeiXinParamesUtil.appsecret;

        String query_menu_create_url =  WeiXinParamesUtil.query_menu_create_url;

        String accessToken = accessTokenUtil.getAccessToken(AppID,AppSecret);

        // 拼装创建菜单的url
        String url =query_menu_create_url.replace("ACCESS_TOKEN", accessToken);

        String result= HttpUtil.get(url);

        return result;
    }

    /**
     * 组装菜单数据
     *
     * @return
     */
    private static Menu getMenu() {

        CommonButton btn21 = new CommonButton();
        btn21.setName("当季推荐");
        //菜单的响应动作类型，view表示网页类型，click表示点击类型，miniprogram表示小程序类型
        btn21.setType("view");
        btn21.setUrl("http://nt-wxd.lxnantong.com/weChat/index.html#/cate/list");

        CommonButton btn22 = new CommonButton();
        btn22.setName("公共服务");
        btn22.setType("view");
        btn22.setUrl("http://nt-wxd.lxnantong.com/weChat/index.html#/publicService/list");

        CommonButton btn23 = new CommonButton();
        btn23.setName("春暖花开");
        btn23.setType("view");
        btn23.setUrl("http://nt-wxd.lxnantong.com/weChat/index.html#/beauty/index");

        CommonButton btn24 = new CommonButton();
        btn24.setName("博物院实名预约");
        btn24.setType("view");
        btn24.setUrl("http://fyb.limachufa.cn/scenic-appointment/consumer/index.html?id=5e901a68e4b015282dfe0cb9#/scenic/list");

        CommonButton btn25 = new CommonButton();
        btn25.setName("预约核销");
        btn25.setType("view");
        btn25.setUrl("http://fyb.limachufa.cn/scenic-appointment/consumer/index.html#/proprietor/login");


        /**
         * 微信：  mainBtn1,mainBtn2,mainBtn3底部的三个一级菜单。
         */

        ComplexButton mainBtn1 = new ComplexButton();
        mainBtn1.setName("在线预订");
        mainBtn1.setType("view");
        mainBtn1.setUrl("http://nt-wxd.lxnantong.com/weChat/index.html#/index?response_type=code");


        ComplexButton mainBtn2 = new ComplexButton();
        mainBtn2.setName("当季服务");
        mainBtn2.setSub_button(new CommonButton[] { btn21, btn22, btn23, btn24, btn25 });


        ComplexButton mainBtn3 = new ComplexButton();
        mainBtn3.setName("个人中心");
        mainBtn3.setType("view");
        mainBtn3.setUrl("http://nt-wxd.lxnantong.com/weChat/index.html#/personalCenter/index");


        /**
         * 封装整个菜单
         */
        Menu menu = new Menu();
        menu.setButton(new Button[] { mainBtn1, mainBtn2, mainBtn3 });

        return menu;
    }


    /**
     * 创建菜单
     *
     * @return 0表示成功，其他值表示失败
     */
    @PostMapping(value = "/createEMenu")
    public boolean createEMenu(String tenantId) {

//        BaseConfigDto baseConfigDto = storeConfigService.queryById(tenantId);
//
//        String AppID = baseConfigDto.getWxAppid();
//        String AppSecret = baseConfigDto.getWxAppSecret();


        String AppID = WeiXinParamesUtil.wxAppid;
        String AppSecret = WeiXinParamesUtil.appsecret;

        String menu_create_url =  WeiXinParamesUtil.menu_create_url;

        String accessToken = accessTokenUtil.getAccessToken(AppID,AppSecret);

        Menu menu = gete_testMenu();

        // 拼装创建菜单的url
        String url =menu_create_url.replace("ACCESS_TOKEN", accessToken);

        // 将菜单对象转换成json字符串
        // false表示不跳过空值
        cn.hutool.json.JSONObject json = cn.hutool.json.JSONUtil.parseObj(menu, true);
        logger.info("菜单....menu={}",json.toString());

        String result= HttpUtil.post(url, json.toString());
        cn.hutool.json.JSONObject jsonObject = cn.hutool.json.JSONUtil.parseObj(result);
        if(null != jsonObject){
            if(0 != jsonObject.getInt("errcode")){
                logger.error("创建菜单失败......返回={}",jsonObject.toString());
                return false;
            }else{
                return true;
            }
        }

        return false;
    }
    /**
     * 组装e游管家菜单数据
     *
     * @return
     */
    private static Menu gete_testMenu() {

        CommonButton btn21 = new CommonButton();
        btn21.setName("景区预约");
        //菜单的响应动作类型，view表示网页类型，click表示点击类型，miniprogram表示小程序类型
        btn21.setType("view");
        btn21.setUrl("https://testccb.limachufa.cn/scenic-appointment/consumer/index.html?id=5eb69fe4e4b0366fc46c180c#/scenic/list");

        CommonButton btn22 = new CommonButton();
        btn22.setName("入园核实");
        btn22.setType("view");
        btn22.setUrl("https://testccb.limachufa.cn/scenic-appointment/consumer/index.html#/proprietor/login");



        /**
         * 微信：  mainBtn1,mainBtn2,mainBtn3底部的三个一级菜单。
         */

        ComplexButton mainBtn1 = new ComplexButton();
        mainBtn1.setName("逛逛景区");
        mainBtn1.setType("view");
        mainBtn1.setUrl("http://store1test.lishicloud.com/weChat/jilin/index.html#/index");


        ComplexButton mainBtn2 = new ComplexButton();
        mainBtn2.setName("复业宝");
        mainBtn2.setSub_button(new CommonButton[] { btn21, btn22 });


        ComplexButton mainBtn3 = new ComplexButton();
        mainBtn3.setName("智能导航");
        mainBtn3.setType("view");
        mainBtn3.setUrl("https://ditu.amap.com/?amapexchange=%2Fsearchmore%2Findex%2Fuser_loc%3D");


        /**
         * 封装整个菜单
         */
        Menu menu = new Menu();
        menu.setButton(new Button[] { mainBtn1, mainBtn2, mainBtn3 });

        return menu;
    }


}




